package service;

import common.Message;
import common.MessageType;

import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

/**
 * 服务器推送新闻
 */
public class SendNewsToAllService implements Runnable {

    @Override
    public void run() {

        // 为了多次推送消息 这里搞个循环
        while (true) {

            System.out.println("请输入服务器 要推送的新闻【输入 exit 表示退出推送服务】");

            Scanner sc = new Scanner(System.in);
            String news = sc.next();
            if (news.equals("exit")) {
                break;
            }

            // 构建消息对象
            Message msg = new Message();
            msg.setSender("服务器");
            msg.setContent(news);
            msg.setMesType(MessageType.MESSAGE_TO_ALL_MES);
            System.out.println("服务器对所有人说：" + news);

            // 遍历当前所有的通讯线程，得到 socket, 并发送 msg 对象
            HashMap<String, ServerConnectClientThread> hm = ManageClientThreads.getHm();

            Set<String> set = hm.keySet();
            for (String key : set) {
                ServerConnectClientThread thread = hm.get(key);
                Socket socket = thread.getSocket();
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(msg);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }

            }

        }

    }
}
